<?php
class Tourismevaluate extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('tourism_order_reviews_model', 'tourism_order_reviews');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
//        $this->load->model('tourism_order_refund_model', 'tourism_order_refund');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
    }

    public function evaluate($orderId = 0)
    {
        $result = $this->tourism_order->findAliasName($orderId);
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单不存在');
        }
        $orderInfo = $result->row();
        if ($orderInfo->order_state != 3 && $orderInfo->order_status != 5) {
            $this->alertJumpPre('订单状态有误,评价失败');
        }
        $orderProduct = $this->tourism_order_product->findByOrderId($orderId);
        if($orderProduct->num_rows() <= 0){
            $this->alertJumpPre('订单有误');
        }
        $this->data['orderProduct'] = $orderProduct->result();
        $this->data['orderInfo'] = $orderInfo;
        $this->load->view('tourism/tourismevaluate/evaluate', $this->data);
    }

    public function evaluatePost()
    {
        $postData = $this->input->post();
        $order_id = $postData['order_id'];
        $tourismOrder = $this->tourism_order->findById($order_id);

        if ($tourismOrder->num_rows() <= 0) {
            $this->alertJumpPre('该订单不存在');
        }
        $tourismOrder = $tourismOrder->row();

        //订单已评价
        if ($tourismOrder->order_state == 4 || $tourismOrder->order_status == 6) {
            $this->alertJumpPre('该订单已评价');
        }

        if ($tourismOrder->order_state != 3 && $tourismOrder->order_status != 5) {
            $this->alertJumpPre('订单状态不有误');
        }
        $orderProduct = $this->tourism_order_product->findByOrderId($order_id);
        if ($orderProduct->num_rows() <= 0) {
            $this->alertJumpPre('订单有误');
        }
        $orderProduct = $orderProduct->result();

        $this->db->trans_begin();
        $orderProductProfit = $this->tourism_order_product->findOrderProductProfit($order_id);

        $profit = $this->operatingProfit($orderProductProfit);
        if (!empty($tourismOrder->seller_uid) && $tourismOrder->transport_cost > 0) {
            $freight = $this->distributionFreight($tourismOrder);
            if (!$profit || !$freight) {
                $this->db->trans_rollback();
                $this->alertJumpPre('评价失败,请刷新后尝试');
            }
        }

        $orderReviews = array();
        foreach ($orderProduct as $key=>$value) {
            $orderReviews[$key]['order_id']          = $value->order_id;
            $orderReviews[$key]['order_product_id']  = $value->order_product_id;
            $orderReviews[$key]['goods_attr_id']     = $value->goods_attr_id;
            $orderReviews[$key]['goods_image']       = $value->goods_image;
            $orderReviews[$key]['attribute_value']   = $value->attribute_value;
            $orderReviews[$key]['goods_name']        = $value->goods_name;
            $orderReviews[$key]['uid']               = $this->uid;
            $orderReviews[$key]['user_name']         = $tourismOrder->user_name;
            $orderReviews[$key]['personal_photo']    = $this->personalPhoto;
            $orderReviews[$key]['user_content']      = $postData['user_content'][$key];
            $orderReviews[$key]['status']            = 2;
            $orderReviews[$key]['review_score']      = $postData['review_score'][$key];
            $orderReviews[$key]['created_at']        = date('Y-m-d H:i:s');
            $orderReviews[$key]['updated_at']        = '0000-00-00 00:00:00';
        }

        $result = $this->tourism_order_reviews->insertBatch($orderReviews);
        $states = $this->tourism_order->updateByOrderId($order_id, array('order_state' => 4, 'order_status' => 6, 'reviews_time' => date('Y-m-d H:i:s')));
        if ($this->db->trans_status() === FALSE || !$result || !$states || !$profit) {
            $this->db->trans_rollback();
            $this->alertJumpPre('评价失败,请刷新后尝试');
        } else {
            $this->db->trans_commit();
            $this->success('tourism/user/orderList','','评价成功');
        }
    }


    /***
     * 分钱操作  1，给账户分钱
     *          2，插入分钱记录
     *          3，插入分润记录
     * @param $orderProductProfit
     * @return bool
     */
    public function operatingProfit($orderProductProfit)
    {
        $accountLogData = array();
        $userAccountData = array();
        foreach ($orderProductProfit->result() as $key => $item) {
            if ($item->uid <= 0 || $item->account <= 0) {
                continue;
            }
            $account_name = getAccountNameByAccountID($item->account_type); //可提现或月结 （字段）

            if ($item->as == 2) { //减
                $total_name = 'outlay_total';  //总支出
                $total_amount = $item->account;
            } else {
                $total_name = 'income_total';  //总收入
                $total_amount = $item->account;
            }

            $this->user_account->updateUserAccountProfit($account_name, $total_name, $total_amount, $item);

            $userAccountData[$item->uid]['uid'] = $item->uid;
            if ($item->account_type == ACCOUNT_TYPE_MONTH) { //到付
                $type = DFPROFIT;
            } else { //在线利润
                $type = ZFPROFIT;
            }
            $accountLogData[$key]           = $item;
            $accountLogData[$key]->order_id = $item->order_product_id;
            $accountLogData[$key]->type     = $type;
        }
        if (empty($accountLogData)) { //分润数据为空
            return true;
        }
        $accountLog = $this->account_log->insertBatchAccountLog($accountLogData);
        if (!$accountLog) {
            return false;
        }
        return true;
    }

    /**
     * 给供应商 分运费的钱
     * @param $tourismOrder
     * @return bool
     */
    public function distributionFreight($tourismOrder)
    {
        $freight = $this->user_account->updateUserFreight($tourismOrder->seller_uid, $tourismOrder->transport_cost);

        $userAccount['order_id']     = $tourismOrder->order_id;
        $userAccount['uid']          = $tourismOrder->seller_uid;
        $userAccount['amount']       = $tourismOrder->transport_cost;
        $userAccount['amount_carry'] = $tourismOrder->transport_cost + $tourismOrder->amount_carry;
        $userAccount['type']         = TOURISMFREIGHT;

        $log = $this->account_log->insertAccountLogFreight($userAccount);

        if (!$freight || !$log) {
            return false;
        }
        return true;
    }
}